/**
 *    Copyright 2012 Geensoft S.A.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 **/
package ar.com.greensoft.neosystem.services.impl;

import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Logger;

import javax.ejb.Stateless;
import javax.inject.Inject;

import org.apache.commons.codec.binary.Hex;

import ar.com.greensoft.neosystem.services.Encoded;
import ar.com.greensoft.neosystem.services.PasswordEncoder;
import ar.com.greensoft.neosystem.services.Encoded.Algoithm;

/**
 * @author Jorge E. Villaverde
 *
 */
@Stateless
@Encoded(Algoithm.HEX)
public class MD5HexPasswordEncoder implements PasswordEncoder {
	@Inject
	private Logger logger;

	@Override
	public String encodePassword(String rawPass) {
		logger.info("Encodign password: " + rawPass);
		return getHEX(getMD5(rawPass));
	}

	@Override
	public boolean isPasswordValid(String encPass, String rawPass) {
		return encPass.equals(getHEX(getMD5(rawPass)));
	}
	
	public synchronized byte[] getMD5(String input){
		MessageDigest messageDigest;
		try {
			messageDigest = MessageDigest.getInstance("MD5");
			messageDigest.reset();
			messageDigest.update(input.getBytes(Charset.forName("UTF8")));
			final byte[] resultByte = messageDigest.digest();
			return resultByte;
		} catch (NoSuchAlgorithmException e) {
			System.err.println(e.getMessage());
		}
		return null;
	}
	
	public synchronized String getHEX(byte[] input){
		final String result = new String(Hex.encodeHex(input));
		return result;
	}
}
